package com.tj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tj.pojo.Category;
import com.tj.pojo.Employee;
import com.tj.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 菜品分类信息分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    private Result<Page<Category>> page(int page,int pageSize) {

        //1.获取分页数据
        List<Category> res=categoryService.page(page,pageSize);

        //2.生成Page类并赋值
        Page<Category> r=new Page<>();
        r.setRecords(res);
        r.setTotal(res.size());

        //3.根据结果是否为空,返回相应数据
        if(res.size()!=0)  return Result.success(r);
        else return Result.error("没有数据");
    }

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping
    private Result<String> addCategory(@RequestBody Category category, HttpServletRequest request) {

        // 1.判断该种类是否存在
        Employee res = categoryService.getByName(category);
        if(res!=null)  return Result.error("添加失败");

        //2.设置创建时间，更新时间
        Date date=new Date();
        category.setCreateTime(date);
        category.setUpdateTime(date);

        //3.设置id,创始人(==id),更新人(==id),status
        category.setId((Long)request.getSession().getAttribute("employee"));
        category.setId(category.getId());
        category.setCreateUser(category.getId());
        category.setUpdateUser(category.getId());

        //4.添加信息到数据库
        categoryService.addCategory(category);
        return Result.success("添加成功");
    }

    /**
     * 删除分类信息
     * @param ids
     * @return
     */
    @DeleteMapping
    private Result<String> deleteById(Long ids){

        //1.获取删除影响列数
        int res=categoryService.deleteById(ids);

        //2.根据res,返回不同结果
        if(res>0) return Result.success("删除成功");
        else if(res==-1) return Result.error("无法删除");
        else return Result.error("删除失败");
    }

    @GetMapping("/list")
    private Result<List<Category>> getCategoryList() {

        //1.获取所有菜品
        List<Category> res = categoryService.getAll();

        //2.返回结果
        return  Result.success(res);
    }
}
